package com.zy.DingDongServer.service;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;

/*
 * code for class DAliyunMsgService
 * @param null
 * 阿里云的短信服务
 * @version 1.0.0
 * @return
 * @author Zhou Yun
 * @date 2022/4/13 10:49
 **/
@Component
public class DAliyunMsgService {
    /*
     * AccessKey ID: LTAI5t9TD4tcHwJwTsP2nkcm
       AccessKey Secret: JBvD9VgeDDacaIipR06FsYziGdnmN8
     **/
    //调用阿里云的短信服务，发生验证码到指定电话号码中。
    public boolean sendCheckCode(String phoneNum,String checkCode){
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5t9TD4tcHwJwTsP2nkcm", "JBvD9VgeDDacaIipR06FsYziGdnmN8");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        //设置域名
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2022-04-13");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        //要发送的手机号
        request.putQueryParameter("PhoneNumbers", phoneNum);
        //放置签名名称
        request.putQueryParameter("SignName", "阿里云短信测试");
        //模板code
        request.putQueryParameter("TemplateCode", "SMS_154950909");
        //模板参数变量
        request.putQueryParameter("TemplateParam", "{\"code\":\""+ checkCode +"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            String jsonStr=response.getData();
            Map maps = (Map)JSON.parse(jsonStr);
            if (maps.get("Message").equals("OK")){
                return true;
            }else {
                System.out.println(jsonStr);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //生成6位随机数字
    public String generateCheckCode(){
        Random random = new Random(System.currentTimeMillis());
        String checkCode = String.valueOf((int) (random.nextDouble() * (1000000 - 100000 + 1) + 100000));
        return checkCode;
    }
}
